<template>
  <div class="content-wrap tables-time">
    <div class="content-box">
      <div :class="{ 'content-left w0': collapseIconLeft, 'content-left': !collapseIconLeft }">
        <div class="filter-wrap">
          <Button size="small" type="info" @click="singleTableQueryBtnClickHandle">单表查询</Button>
          <Button size="small" type="primary" @click="userQueryBtnClickHandle">用户查询</Button>
          <Button size="small" type="warning" @click="tradeQueryBtnClickHandle">行业查询</Button>
        </div>
        <div class="table-wrap">
          <Table
            ref="table"
            class="table-item"
            :columns="tableColums"
            :loading="tableLoading"
            @on-row-click="tableClickHandle"
            size="small"
            :height="tableHeight"
            :data="tableData"
            :no-data-text="tableHint"
            highlight-row
          ></Table>
          <div class="page-box tc">
            <Page
              :total="tablePageData.total"
              :current="tablePageParams.pageNum"
              size="small"
              simple
              @on-change="changeTablePageHandle"
              :page-size="tablePageParams.pageSize"
            />
            <span class="reset-btn" title="重置" @click="restTableHandle">
              <Icon type="md-refresh-circle" />
            </span>
          </div>
        </div>
      </div>
      <div :class="centerClass">
        <div class="top-box">
          <Card :bordered="false">
            <div slot="title" class="tc card-head">
              <span class="collapse-left-icon collapse-icon" @click="collapseHandler('left')">
                <span v-if="collapseIconLeft" title="缩小">
                  <Icon type="icon iconfont icon-xianghou" />
                </span>
                <span v-else title="放大">
                  <Icon type="icon iconfont icon-xiangqian" />
                </span>
              </span>
              <Select
                size="small"
                style="width:160px;margin-right: 10px;"
                :disabled="!currentMeterId"
                v-model="selectedType"
                @on-change="changeDateType"
              >
                <Option v-for="item of selectDateTypes" :key="item.value" :value="item.value">{{ item.name }}</Option>
              </Select>
              <DatePicker
                transfer
                type="daterange"
                show-week-numbers
                placement="bottom-end"
                placeholder="选择日期"
                size="small"
                split-panels
                @on-change="changeBoxlineFilterDate"
              />
              <span class="collapse-right-icon collapse-icon" @click="collapseHandler('right')">
                <span v-if="collapseIconRight" title="缩小">
                  <Icon type="icon iconfont icon-xiangqian" />
                </span>
                <span v-else title="放大">
                  <Icon type="icon iconfont icon-xianghou" />
                </span>
              </span>
            </div>
            <div class="chart-box">
              <e-boxline
                :id="id()"
                :chartData="eBoxlineChartData"
                @q-brushEnd="boxLineBrushEndHandle"
                @q-finished="boxLineFinishedHandle"
                v-if="selectedType === 'gl'"
              />
              <div v-if="selectedType === 'tz'" style="width:100%;height:100%">
                <e-line :id="id()" :chartData="zxData" />
              </div>
              <Spin fix v-show="eBoxlineSpinLoading">加载中...</Spin>
              <Button
                type="warning"
                size="small"
                v-if="selectedType === 'tz'"
                class="play-btn"
                :loading="elinePlayStopEvent"
                @click="handleElinePlay"
                >曲线播放</Button
              >
              <div class="play-module" v-if="elinePlayStopEvent"></div>
            </div>
          </Card>
        </div>
        <div class="bottom-box">
          <Card :bordered="false">
            <div slot="title" class="clearfix">
              <span class="title-text">{{ midBottomTit }}</span>
            </div>
            <div :class="hBar3dSpinLoading ? 'chart-box' : 'chart-box overY'">
              <h-bar3d
                v-if="selectedType === 'gl' && hBar3dData"
                :id="id()"
                :chartData="hBar3dData"
                :defaultOptions="hBar3dOptions"
              />
              <e-line v-if="selectedType === 'tz'" :id="id()" :chartData="zbzData" height="65px" />
              <e-line
                v-if="selectedType === 'tz'"
                :id="id()"
                :chartData="eLineData"
                height="360px"
                @q-click="eLineClickHandle"
                @q-brushEnd="eLineBrushEndHandle"
                @q-brush="eLineBrushHandle"
                @q-finished="eLineFinishedHandle"
                @q-globalcursortaken="eLineGlobalcursortakenHandle"
              />
              <Spin fix v-show="hBar3dSpinLoading">加载中...</Spin>
            </div>
          </Card>
        </div>
      </div>
      <div :class="{ 'content-right w0': collapseIconRight, 'content-right': !collapseIconRight }">
        <div class="top-box">
          <Card :bordered="false">
            <div slot="title" class="clearfix">
              <span class="fl">小时用气规律</span>
              <div class="fr">
                <Button @click="saveParamsWithMeter" :loading="saveParamsBtnLoading" size="small" type="info"
                  >保存</Button
                >
              </div>
            </div>
            <div class="chart-box">
              <div class="usegas-info">
                <p class="title">绝对在用气的小时</p>
                <div class="list">
                  <Tag color="geekblue" v-for="item of definitelyGas" :key="item">{{ item }}</Tag>
                  <span v-show="definitelyGas.length === 0">暂无</span>
                </div>
                <p class="title">集中用气小时</p>
                <div class="list">
                  <Tag color="blue" v-for="item of focusGas" :key="item">{{ item }}</Tag>
                  <span v-show="focusGas.length === 0">暂无</span>
                </div>
                <p class="title">没有用气的小时</p>
                <div class="list">
                  <Tag color="lime" v-for="item of notGas" :key="item">{{ item }}</Tag>
                  <span v-show="notGas.length === 0">暂无</span>
                </div>
              </div>
              <div class="peak-gas-info">
                <Card v-for="(item, index) of peakGasInfoList" :key="index" class="list" :bordered="false">
                  <div slot="title">用气高峰时段{{ index + 1 }}</div>
                  <a href="javascript:;" title="关闭" slot="extra" @click="deletePeakGas(index)">
                    <Icon type="ios-close-circle-outline" />
                  </a>
                  <div class="item">
                    <Row>
                      <i-col span="8"><span class="name">时段</span></i-col>
                      <i-col span="16"
                        ><span class="text"
                          >{{ item.startHours || '暂无' }} - {{ item.endHours || '暂无' }}</span
                        ></i-col
                      >
                    </Row>
                    <Row>
                      <i-col span="8"><span class="name">平均用气量</span></i-col>
                      <i-col span="16"
                        ><span class="text">{{ item.AVG || '暂无' }}</span></i-col
                      >
                    </Row>
                    <Row>
                      <i-col span="8"><span class="name">用气量的波动</span></i-col>
                      <i-col span="16"
                        ><span class="text">{{ item.standardDiviation || '暂无' }}</span></i-col
                      >
                    </Row>
                  </div>
                </Card>
              </div>
              <div class="usegas-average" v-show="showUsegasModeList">
                <p class="title">
                  {{ cAeUsegasMode && cAeUsegasMode.label
                  }}<span v-show="cAeUsegasWeekStr">({{ cAeUsegasWeekStr }})</span>
                </p>
                <Card class="list" :bordered="false" v-for="(item, index) of usegasModeList" :key="index">
                  <div slot="title">模式</div>
                  <a href="javascript:;" title="关闭" slot="extra" @click="deleteUsegasMode(index)">
                    <Icon type="ios-close-circle-outline" />
                  </a>
                  <div class="chart-box">
                    <e-line
                      :id="'average' + index"
                      :chartData="modifycAeChartData(item.avgChartData.axiasList, item.avgChartData.serList)"
                    />
                  </div>
                </Card>
              </div>
            </div>
          </Card>
        </div>
        <div class="bottom-box">
          <Card :bordered="false">
            <div slot="title">
              详情
            </div>
            <div class="detail-box">
              <meter-detail
                :id="id()"
                :currentMeterId="currentMeterId"
                :content="meterDetail"
                :columnNames="meterDetailColumns"
              />
            </div>
          </Card>
        </div>
      </div>

      <!-- 单表查询 -->
      <Modal
        class="modal-p10"
        v-model="singleTableQueryModelFlag"
        title="单表查询"
        width="360"
        @on-cancel="handleModalCancel"
      >
        <Form :model="sigleTaleQueryFormData" label-position="top" @submit.native.prevent="singleTableQueryHandle">
          <FormItem label="表号">
            <Input v-model="sigleTaleQueryFormData.meterId" ref="meterId" placeholder="请输入表号" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="primary" @click="singleTableQueryHandle">查询</Button>
        </div>
      </Modal>
      <!-- 用户查询 -->
      <Modal class="modal-p10" v-model="userQueryModelFlag" title="用户查询" width="360" @on-cancel="handleModalCancel">
        <Form :model="userQueryFormData" label-position="top">
          <FormItem label="用户编号">
            <Input v-model="userQueryFormData.unitId" placeholder="请输入用户编号" />
          </FormItem>
          <FormItem label="用户名称">
            <Input v-model="userQueryFormData.unitName" placeholder="请输入用户名称" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="primary" @click="userQueryHandle">查询</Button>
        </div>
      </Modal>

      <!-- 行业查询 -->
      <Modal
        v-model="tradeQueryModelFlag"
        class="clear-body-padding"
        title="行业查询"
        width="96%"
        @on-cancel="handleModalCancel"
        :styles="{ top: '30px', height: '85%' }"
      >
        <div
          :id="id()"
          :is="tradeQueryTemplate"
          :fetchData="fetchRectTreeMapData"
          :chartData="treemapData"
          @q-click="rectTreeMapClickHandle"
        ></div>
      </Modal>

      <!-- 展示日历和平均用气折线图 -->
      <Modal
        v-model="cAeModuleFlag"
        class="clear-body-padding"
        title="详情"
        width="96%"
        @on-ok="handlecAeModuleOk"
        @on-cancel="handlecAeModuleCancel"
        :styles="{ top: '30px', height: '85%' }"
      >
        <div
          :is="calendarAndElineTpl"
          :calendarData="cAeCalendarData"
          :eLineData="cAeElineData"
          @change-usegas-mode="changeUsegasMode"
          @change-show-date="changeShowDate"
        ></div>
      </Modal>
    </div>
  </div>
</template>
<script>
import {
  each,
  last,
  merge,
  get,
  head,
  split,
  compact,
  some,
  concat,
  isUndefined,
  isEqual,
  includes,
  uniq,
  join
} from 'lodash'
import { nanoid } from 'nanoid'
import dayjs from 'dayjs'
import tableColums from './tableColums'
import {
  tableData,
  rectTreeMap,
  meterDetail,
  ajaxEBoxlineData,
  eBar3d,
  paramsByMeterId,
  saveParamsByMeterId,
  getJhData
} from '@/api/gasLawTablesTime'
import setTableHeightMixin from '@/mixins/setTableHeight'
import tableKeyUpToolMixin from '@/mixins/tableKeyUpTool'
import {
  eTreemapOptions,
  eBoxlineOptions,
  hBar3dOptions,
  eLineOptions,
  jhElineOptions,
  eCalendarOptions
} from './chartOptions/index'
import meterDetailColumns from './meterDetailColumns'
import week from './week'

export default {
  name: 'tables-day',
  mixins: [setTableHeightMixin, tableKeyUpToolMixin],
  components: {
    MeterDetail: () => import('@/commons/MeterDetail'),
    ETreemap: () => import('@/commons/charts/ETreemap'),
    EBoxline: () => import('@/commons/charts/EBoxline'),
    ELine: () => import('@/commons/charts/ELine'),
    HBar3d: () => import('@/commons/charts/HBar3d'),
    CalendarAndELine: () => import('./components/CalendarAndELine')
  },
  data() {
    return {
      selectDateTypes: Object.freeze([
        {
          name: '小时用气统计规律',
          value: 'gl'
        },
        {
          name: '小时用气特征分类',
          value: 'tz'
        }
      ]),
      tableColums: tableColums,
      tableLoading: false,
      tableData: [],
      tableHint: '',
      tablePageParams: {
        pageNum: 1,
        pageSize: 20
      },
      tablePageData: {
        total: 0
      },
      eBoxlineSpinLoading: false,
      hBar3dSpinLoading: false,
      currentMeterGasClass: undefined,
      singleTableQueryModelFlag: false, // 控制单表查询模态框显示、隐藏
      userQueryModelFlag: false, // 用户查询模态框显示、隐藏
      tradeQueryModelFlag: false, // 行业查询模态框显示、隐藏
      sigleTaleQueryFormData: {
        meterId: undefined
      },
      userQueryFormData: {
        unitId: undefined,
        unitName: undefined
      },
      tradeQueryTemplate: null,
      meterDetail: {},
      treemapData: null,
      currentMeterId: undefined,
      currentMonth: null,
      collapseIconRight: false,
      collapseIconLeft: false,
      collapseIcon: false,
      hBar3dData: null,
      paramsType: 'tableTime',
      eBoxlineChartData: null, // 中间区域箱线图数据
      useGasInfo: {
        definitelyGas: '',
        focusGas: '',
        notGas: ''
      },

      boxLinePosList: [], // 箱线图渲染数据x坐标范围
      boxLineSelectedTime: [], // 用户选框选中数据
      peakGasInfoList: [], // 用气高峰列表
      saveParamsBtnLoading: false, // 保存按钮加载状态
      eBoxlineFilterData: {
        startTime: undefined,
        endTime: undefined
      },
      selectedType: undefined,
      candlestickSelectedTime: null,
      bcData: null,
      eLineData: null,
      zbzData: null,
      zxData: null,
      hasMoveFlag: true,
      elinePlayTimer: null,
      elinePlayStopEvent: false,
      jlPointPosi: [],
      jlSelectedData: [],
      selecteElineDataByjl: [],
      cAeModuleFlag: false,
      cAeCalendarData: null,
      cAeElineData: null,
      calendarAndElineTpl: null,
      cAeUsegasMode: null,
      cAeUserSelectedMode: null,
      cAeUsegasWeekList: [],
      cAeUsegasWeekStr: '',
      showcAeUsegasWeek: false,
      currentSelecteAreaMode: null,
      usegasModeList: []
    }
  },
  computed: {
    defaultDate() {
      return this.$config.nowDate
    },
    id() {
      return nanoid
    },
    hBar3dOptions() {
      return hBar3dOptions
    },
    /**
     * desc: 绝对在涌起的小时
     */
    definitelyGas() {
      return this.useGasInfo.definitelyGas ? compact(split(this.useGasInfo.definitelyGas, ',')) : []
    },
    /**
     * desc: 集中用气的小时
     */
    focusGas() {
      return this.useGasInfo.focusGas ? compact(split(this.useGasInfo.focusGas, ',')) : []
    },
    /**
     * desc: 没有用气的小时
     */
    notGas() {
      return this.useGasInfo.notGas ? compact(split(this.useGasInfo.notGas, ',')) : []
    },
    meterDetailColumns() {
      return meterDetailColumns
    },
    currentDate() {
      return dayjs(this.defaultDate).format('YYYY-MM')
    },
    midBottomTit() {
      return this.selectedType === 'tz' ? '小时用气模式聚类图谱' : '高峰期用气量分析'
    },
    showUsegasModeList() {
      return this.usegasModeList.length > 0
    },
    centerClass() {
      let _cls = 'content-center'
      if (this.collapseIconLeft) {
        _cls += ' l0'
      }
      if (this.collapseIconRight) {
        _cls += ' r0'
      }
      return _cls
    }
  },
  watch: {
    tableData(newData, oldData) {
      if (!isEqual(newData, oldData)) {
        this.removeEvent()
        this.indexHasCandlestickDatezoom = true
        this.meterDetail = {}
        this.showKxianBackBtn = false
        this.barlineData = null
        this.zhexianDayData = null
        this.candlestickData = {}
        this.selectedIndex = undefined
        this.currentMeterId = undefined
      }
    }
  },
  mounted() {
    this.fetchTableData()
  },
  methods: {
    /**
     * desc: 清空规律图表数据
     * param {type}
     * return {type} void
     */
    clearChartDataByGl() {
      this.hBar3dData && (this.hBar3dData.series = [])
      this.eBoxlineChartData && (this.eBoxlineChartData.series = [])
    },
    /**
     * desc: 清空特征图标数据
     * param {type}
     * return {type} void
     */
    clearChartDataByTz() {
      this.bcData && (this.bcData.series = [])
      this.eLineData && (this.eLineData.series = [])
      this.zbzData && (this.zbzData.series = [])
      this.zxData && (this.zxData.series = [])
    },
    /**
     * desc: 还原数据
     * param {type}
     * return {type} void
     */
    originalData() {
      this.tablePageData.total = 0
      this.selectedIndex = undefined
    },
    /**
     * @msg: 显示模态框，阻止页面键盘事件
     * @param {type}
     * @return:
     */
    handleModalCancel() {
      this.containerOnKeyup()
    },
    /**
     * desc: 阻止键盘操作表格
     * param {type}
     * return {type} void
     */
    stopOnKeyup() {
      this.hasMoveFlag = true
    },
    /**
     * desc: 继续键盘操作表格
     * param {type}
     * return {type} void
     */
    containerOnKeyup() {
      this.hasMoveFlag = false
    },
    /**
     * @msg: 翻页操作
     * @param {type}
     * @return:
     */
    changeTablePageHandle(data) {
      this.tablePageParams = {
        ...this.tablePageParams,
        pageNum: data
      }
      this.$nextTick(() => {
        this.fetchTableData()
      })
    },
    /**
     * desc: 主要是为了和绑定键盘事件的minx对应而添加的方法
     * param {type}
     * return {type} void
     */
    currentSelectedTableData() {
      const currentData = this.tableData[this.selectedIndex]
      this.selectedData = currentData
      const { meterId } = currentData
      this.currentMeterId = meterId
      this.$nextTick(() => {
        if (this.selectedType === 'tz') {
          this.fetchJhData()
        } else if (this.selectedType === 'gl') {
          this.getBlineAndZlineAndMeterDetail()
        }
        this.fetchParamsByMeterId()
        this.fetchMeterDetail(this.currentMeterId)
      })
    },
    /**
     * desc: 左侧表格行点击
     *       1、绑定键盘事件
     *       2、筛选出当前点击行数据
     * param {type}
     * return: void
     */
    tableClickHandle(row = {}, index) {
      if (this.selectedIndex !== index) {
        const { meterId } = row
        this.currentMeterId = meterId
        if (isUndefined(this.selectedIndex)) {
          this.containerOnKeyup()
          this.dispatchEvent()
        }
        this.selectedIndex = index
        this.$nextTick(() => {
          this.selectedData = this.getTabClickRowData()
          this.currentSelectedTableData()
        })
      }
    },
    /**
     * @msg: 选取表格当前选中的数据项
     * @param {type}
     * @return: 当前点击行数据 || []
     */
    getTabClickRowData() {
      return this.tableData[this.selectedIndex] || []
    },
    /**
     * desc: 获取箱线图和柱状图数据和表详情
     * param {type}
     * return:
     */
    getBlineAndZlineAndMeterDetail() {
      const { meterId } = this.selectedData
      this.currentMeterId = meterId
      const retMonth = dayjs(this.defaultDate).format('YYYY-MM')
      this.currentMonth = retMonth
      this.hBar3dData = null
      this.getEBoxlineData({
        meterId,
        ...this.eBoxlineFilterData
      })
    },
    /**
     * desc: 获取中间区域箱线图数据
     * param {type}
     * return:
     */
    getEBoxlineData(params) {
      this.stopOnKeyup()
      this.eBoxlineSpinLoading = true
      this.cAeElineData = null
      this.jlSelectedData = []
      ajaxEBoxlineData({ ...params })
        .then(res => {
          if (res.date) {
            const { list = [], ...rest } = res.date
            this.modifyEBoxlineData(list)
            this.useGasInfo = {
              ...this.useGasInfo,
              ...rest
            }
          }
        })
        .finally(() => {
          this.containerOnKeyup()
          this.eBoxlineSpinLoading = false
        })
    },
    /**
     * desc: 构造中间区域箱线图数据
     * param {type}
     * return:
     */
    modifyEBoxlineData(data = []) {
      const _seriesDaata = []
      const _axisData = []
      each(data, item => {
        const [_a, _b, _c, _d, _f, _g] = item
        _axisData.push(_a)
        _seriesDaata.push({
          name: _a,
          value: [_b, _c, _d, _f, _g]
        })
      })
      this.eBoxlineChartData = merge({}, eBoxlineOptions, {
        xAxis: {
          data: _axisData
        },
        series: [
          {
            data: _seriesDaata
          }
        ]
      })
    },
    /**
     * @msg: 点击单表查询按钮
     * @param {type}
     * @return:
     */
    singleTableQueryBtnClickHandle() {
      this.singleTableQueryModelFlag = true
      this.stopOnKeyup()
      this.$nextTick(() => {
        this.$refs['meterId'].focus()
      })
    },
    /**
     * @msg: 点击用户查询按钮
     * @param {type}
     * @return:
     */
    userQueryBtnClickHandle() {
      this.userQueryModelFlag = true
      this.stopOnKeyup()
    },
    /**
     * @msg: 行业查询
     * @param {type}
     * @return:
     */
    tradeQueryBtnClickHandle() {
      this.stopOnKeyup()
      this.tradeQueryModelFlag = true
      this.tradeQueryTemplate = 'ETreemap'
    },
    /**
     * @msg: 获取表格数据
     * @param {type}
     * @return:
     */
    fetchTableData() {
      this.stopOnKeyup()
      this.tableLoading = true
      this.currentMeterId = undefined
      this.cAeElineData = null
      this.usegasModeList = []
      this.jlSelectedData = []
      // 重新选择表格数据，获取箱线图数据，清空详情数据
      this.peakGasInfoList = []
      tableData({
        ...this.tablePageParams,
        ...this.userQueryFormData,
        ...this.sigleTaleQueryFormData,
        meterGasClass: this.currentMeterGasClass
      })
        .then(res => {
          if (res.date && res.date.list) {
            const { total, list, pageNum, pageSize } = res.date
            this.tablePageParams = {
              ...this.tablePageParams,
              pageNum,
              pageSize
            }
            this.tablePageData = {
              ...this.tablePageData,
              total
            }
            this.tableData = list
            this.$nextTick(() => {
              this.setTableHeight()
            })
          }
          this.tableLoading = false
        })
        .catch(() => {
          this.tableHint = '暂无数据'
          this.tableLoading = false
        })
        .finally(() => {
          this.containerOnKeyup()
        })
    },
    /**
     * @msg: 单表查询
     * @param {type}
     * @return:
     */
    singleTableQueryHandle() {
      this.clearChartDataByGl()
      this.clearChartDataByTz()
      this.originalData()
      this.fetchTableData()
      this.containerOnKeyup()
      this.singleTableQueryModelFlag = false
    },
    /**
     * @msg: 用户查询
     * @param {type}
     * @return:
     */
    userQueryHandle() {
      this.clearChartDataByGl()
      this.clearChartDataByTz()
      this.originalData()
      this.fetchTableData()
      this.containerOnKeyup()
      this.userQueryModelFlag = false
    },
    /**
     * @msg: 整理矩形树图数据
     * @param {type}
     * @return:
     */
    modifyTreemapData(data = []) {
      const _serList = []
      each(data, item => {
        const { count, meterGasClass } = item
        _serList.push({
          name: meterGasClass,
          value: count
        })
      })
      this.treemapData = merge({}, eTreemapOptions, {
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    /**
     * @msg: 获取矩形树图数据
     * @param {type}
     * @return:
     */

    fetchRectTreeMapData() {
      this.stopOnKeyup()
      rectTreeMap()
        .then(res => {
          if (res.date) {
            this.modifyTreemapData(res.date)
          }
        })
        .finally(() => {
          this.containerOnKeyup()
        })
    },
    /**
     * @msg: 方块图表点击
     * @param {type}
     * @return:
     */
    rectTreeMapClickHandle(params = {}) {
      this.clearChartDataByGl()
      this.clearChartDataByTz()
      const { data = {} } = params
      const { name } = data
      this.currentMeterGasClass = name
      this.tradeQueryModelFlag = false
      this.containerOnKeyup()
      this.tablePageParams = {
        ...this.tablePageParams,
        pageNum: 1
      }
      this.originalData()
      this.$nextTick(() => {
        this.fetchTableData()
      })
    },
    /**
     * @msg: 重置表格数据
     * @param {type}
     * @return:
     */
    restTableHandle() {
      this.userQueryFormData = {
        unitId: undefined,
        unitName: undefined
      }
      this.sigleTaleQueryFormData = {
        meterId: undefined
      }
      this.currentMeterGasClass = undefined
      this.tablePageParams = {
        pageNum: 1,
        pageSize: 20
      }
      this.$nextTick(() => {
        this.fetchTableData()
      })
    },
    /**
     * @msg: 获取表具详情
     * @param {type}
     * @return:
     */
    fetchMeterDetail(meterId) {
      this.stopOnKeyup()
      meterDetail(meterId)
        .then(res => {
          if (res.date) {
            this.meterDetail = res.date
          } else {
            this.meterDetail = null
          }
        })
        .finally(() => {
          this.containerOnKeyup()
        })
    },
    /**
     * @msg: 两侧收缩中间放大
     * @param {type}
     * @return:
     */
    collapseHandler(type) {
      const { collapseIconLeft, collapseIconRight, collapseIcon } = this
      if (type === 'left') {
        this.collapseIconLeft = !collapseIconLeft
      } else {
        this.collapseIconRight = !collapseIconRight
      }
      this.collapseIcon = !collapseIcon
    },
    /**
     * desc: 用户选框操作，筛选出选中的时间轴
     * param {type}
     * return: void
     */
    boxLineBrushEndHandle(params = {}) {
      const _rangeList = get(params, 'areas[0].range')
      const _selTime = []
      each(this.boxLinePosList, item => {
        const [_a, _b] = item
        if (_a >= _rangeList[0] && _a < _rangeList[1]) {
          _selTime.push(_b)
        }
      })
      if (_selTime.length > 0) {
        this.boxLineSelectedTime = _selTime
        this.$nextTick(() => {
          this.fetchHBar3dData()
        })
      }
    },
    /**
     * desc: 图表加载完成获取图形坐标对应的范围
     * param {type}
     * return: void
     */
    boxLineFinishedHandle(chart, data = []) {
      const { _itemLayouts = [], _nameList = [] } = data
      const _posList = []
      each(_itemLayouts, (item, index) => {
        const { ends = [] } = item
        const _first = head(ends)[0]
        const _last = last(ends)[0]
        const _half = (_last - _first) / 2
        const _newFirst = _first + _half
        _posList.push([_newFirst, _nameList[index]])
      })
      if (!isEqual(this.boxLinePosList, _posList)) {
        this.boxLinePosList = _posList
      }
    },
    /**
     * desc: 判断展示的用气信息列表中是否存在相同的选择区域
     * param {type}
     * return: 存在： true 反之: false
     */
    hasPeakHoursInList(data = {}) {
      return some(this.peakGasInfoList, item => {
        const { endHours, startHours } = item
        if (endHours === data.endHours && startHours === data.startHours) {
          return true
        }
      })
    },
    /**
     * desc: 整理3d柱图和用气高峰数据
     * param {data}
     * return: void
     */
    modifyBar3dAndPeakGasData(data = {}) {
      const { listMap = [], AVG, endHours, startHours, standardDiviation } = data
      const _serList = []
      each(listMap, item => {
        const { minValue, maxValue, count } = item
        _serList.push({
          name: minValue + '-' + maxValue,
          y: count,
          min: minValue,
          max: maxValue
        })
      })
      this.peakGasInfoList.push({
        AVG,
        endHours,
        startHours,
        standardDiviation
      })
      this.hBar3dData = merge({}, hBar3dOptions, {
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    /**
     * desc: 用户操作箱线图选择区域后，获取3d柱图数据
     * param {type}
     * return: void
     */

    fetchHBar3dData() {
      this.stopOnKeyup()
      const _startHour = head(this.boxLineSelectedTime)
      const _endHour = last(this.boxLineSelectedTime)
      // 队已经选择了的区域重复选择时避免操作
      if (!this.hasPeakHoursInList({ endHours: _endHour, startHours: _startHour })) {
        const { currentMeterId } = this
        this.hBar3dSpinLoading = true
        eBar3d({
          meterId: currentMeterId,
          endHours: _endHour,
          startHours: _startHour
        })
          .then(res => {
            if (res.date) {
              this.modifyBar3dAndPeakGasData(res.date)
            }
          })
          .finally(() => {
            this.containerOnKeyup()
            this.hBar3dSpinLoading = false
          })
      }
    },
    /**
     * desc: 获取表具对应的保存参数,并展示
     * param {type}
     * return: void
     */
    fetchParamsByMeterId() {
      this.stopOnKeyup()
      const { currentMeterId } = this
      paramsByMeterId({
        meterId: currentMeterId,
        type: this.paramsType
      })
        .then(res => {
          if (res.date) {
            const { text } = res.date
            try {
              const { useGasInfo, peakHoursList } = JSON.parse(text)
              this.useGasInfo = useGasInfo
              this.peakGasInfoList = peakHoursList
            } catch (error) {
              // do nothing
            }
          }
        })
        .finally(() => {
          this.containerOnKeyup()
        })
    },
    /**
     * desc: 保存参数
     * param {type}
     * return: void
     */
    saveParamsWithMeter() {
      const { currentMeterId } = this
      if (!currentMeterId) {
        return this.$Notice.warning({
          title: '提示信息',
          desc: '没有可操作的表具'
        })
      }
      this.saveParamsBtnLoading = true
      let _params = { useGasInfo: this.useGasInfo, peakHoursList: this.peakGasInfoList }
      _params.averageUseGasInfo = {
        usegasMode: this.cAeUsegasMode,
        selecteAreaData: this.usegasModeList
      }
      const _paramsStr = JSON.stringify(_params)
      saveParamsByMeterId({
        meterId: currentMeterId,
        type: this.paramsType,
        text: _paramsStr
      })
        .then(res => {
          this.$Message.success(res.msg)
        })
        .catch(() => {
          this.$Message.success('保存失败')
        })
        .finally(() => {
          this.saveParamsBtnLoading = false
        })
    },
    /**
     * desc: 点击删除用气高峰按钮
     * param {type}
     * return: void
     */
    deletePeakGas(index) {
      this.peakGasInfoList.splice(index, 1)
    },
    /**
     * desc: 选择eboxline上的日期
     * param {type}
     * return: void
     */
    changeBoxlineFilterDate(val = []) {
      const { currentMeterId } = this
      if (!currentMeterId) {
        return this.$Notice.warning({
          title: '操作提示',
          desc: '请选择要查询的表具'
        })
      }
      this.eBoxlineFilterData.startTime = val[0] || undefined
      this.eBoxlineFilterData.endTime = val[1] || undefined
      if (this.selectedType === 'tz') {
        this.fetchJhData()
      } else if (this.selectedType === 'gl') {
        this.getBlineAndZlineAndMeterDetail()
      }
    },
    /**
     * desc: 箱线图上日期类型选择，如 天  月
     * param {type}
     * return: void
     */
    changeDateType(val) {
      if (!this.currentMeterId) {
        return this.$Notice.warning({
          title: '操作提示',
          desc: '请选择要查询的表具'
        })
      }
      if (val === 'tz') {
        this.clearChartDataByGl()
        this.fetchJhData()
      } else if (val === 'gl') {
        this.clearChartDataByTz()
        this.getBlineAndZlineAndMeterDetail()
      }
    },
    /**
     * desc: 获取聚合数据
     * param {type}
     * return: void
     */
    fetchJhData() {
      this.stopOnKeyup()
      this.cAeElineData = null
      this.jlSelectedData = []
      this.usegasModeList = []
      this.hBar3dSpinLoading = true
      this.eBoxlineSpinLoading = true
      let _startTime = this.eBoxlineFilterData.startTime
      let _endTime = this.eBoxlineFilterData.endTime
      _startTime = _startTime && dayjs(_startTime).format('YYYY-MM-DD')
      _endTime = _endTime && dayjs(_endTime).format('YYYY-MM-DD')
      getJhData({
        meterId: this.currentMeterId,
        startTime: _startTime,
        endTime: _endTime
      })
        .then(res => {
          if (res.date) {
            this.modifyJhData(res.date)
          }
        })
        .finally(() => {
          this.containerOnKeyup()
          this.hBar3dSpinLoading = false
          this.eBoxlineSpinLoading = false
        })
    },
    /**
     * desc: 根据点绘制折线图
     * param {type}
     * return: void
     */
    modifyJhData(data = {}) {
      const { drawlabels = [], parallel = [], drawnames = [], draelines = [] } = data
      this.bcData = merge({}, eLineOptions, {
        series: [
          {
            type: 'line',
            data: []
          }
        ]
      })
      const _jlSerList = []
      const _jlAxiasList = []
      const _zbzAxiasList = []
      const _zbzSerList = []
      let _jlAxiasMin = 0
      const _zxSerList = []
      const _zxAxiasList = []
      const _zxlegendList = []
      each(draelines, item => {
        _jlSerList.push({
          type: 'line',
          step: 'end',
          data: item,
          lineStyle: {
            color: '#25f3e6'
          },
          itemStyle: {
            color: '#25f3e6'
          }
        })
      })
      each(drawnames, (item, index) => {
        const [_a, _b, _c] = item
        if (index === 0) {
          _jlAxiasMin = _a
        }
        if (_a < _jlAxiasMin) {
          _jlAxiasMin = _a
        }
        _jlAxiasList.push({
          name: _c + '',
          value: [_a, _b, _c],
          label: {
            show: true,
            formatter: '{b}',
            position: 'left',
            color: '#fff'
          }
        })
      })
      this.eLineData = merge({}, jhElineOptions, {
        title: {
          text: '聚类图'
        },
        toolbox: {
          orient: 'vertical',
          left: 0,
          top: '38%',
          feature: {
            myPlay: {
              show: true,
              title: '查看选中数据详情',
              icon:
                'image://',
              onclick: this.jlShowDateClick
            }
          },
          zlevel: 99
        },
        brush: {
          toolbox: ['lineY', 'clear'],
          throttleType: 'debounce',
          throttleDelay: 300,
          removeOnClick: false
        },
        xAxis: {
          min: _jlAxiasMin
        },
        yAxis: {
          show: false
        },
        series: concat(_jlSerList, {
          type: 'line',
          data: _jlAxiasList,
          lineStyle: {
            color: '#31597d'
          },
          itemStyle: {
            color: '#31597d'
          }
        })
      })
      each(drawlabels, (item, index) => {
        if (index === 0) {
          _zbzSerList.push({
            type: 'line',
            data: item
          })
        } else {
          _zbzSerList.push({
            type: 'line',
            data: item
          })
        }
        _zbzAxiasList.push(index)
      })
      this.zbzData = merge({}, jhElineOptions, {
        title: {
          text: '坐标尺'
        },
        xAxis: {
          axisLabel: {
            formatter: function(val, index) {
              return index
            }
          }
        },
        yAxis: {
          inverse: true
        },
        series: _zbzSerList,
        grid: {
          top: 30
        }
      })
      each(parallel, item => {
        _zxSerList.push({
          type: 'line',
          ...item
        })
        _zxlegendList.push(item.name)
      })
      for (let i = 0; i < 24; i++) {
        _zxAxiasList.push(i + ':00')
      }
      this.zxData = merge({}, eLineOptions, {
        legend: {
          type: 'scroll',
          top: 8,
          left: '3%',
          right: '105',
          itemWidth: 12,
          itemHeight: 8,
          pageIconSize: 12,
          pageTextStyle: {
            color: '#fff'
          },
          pageIconInactiveColor: '#2f4554',
          pageIconColor: '#ccc',
          data: _zxlegendList
        },
        xAxis: {
          type: 'category',
          data: _zxAxiasList
        },
        series: _zxSerList
      })
    },
    /**
     * desc: 曲线播放
     * param {type}
     * return {type} void
     */
    handleElinePlay() {
      if (!this.zxData) {
        return this.$Notice.warning({
          title: '提示信息',
          desc: '没有可播放的数据'
        })
      }
      const { series, xAxis, legend } = this.zxData
      if (series.length < 2) {
        return this.$Notice.warning({
          title: '提示信息',
          desc: '没有可播放的数据'
        })
      }
      const _serList = []
      const _legendList = []
      let _len = 0
      this.elinePlayStopEvent = true
      this.elinePlayTimer = setInterval(() => {
        if (_len >= series.length - 1) {
          this.$Notice.success({
            title: '提示信息',
            desc: '播放结束'
          })
          clearInterval(this.elinePlayTimer)
          this.elinePlayStopEvent = false
        }
        series[_len].lineStyle = {}
        _serList.push(series[_len])
        _legendList.push(legend.data[_len])
        this.zxData = merge({}, eLineOptions, {
          legend: {
            ...legend,
            data: _legendList
          },
          xAxis,
          series: _serList
        })
        _len++
      }, 1000)
    },
    /**
     * desc: 折线图加载完成
     * param {type}
     * return: void
     */
    eLineFinishedHandle(chart = {}) {
      const { _chartsViews = [] } = chart
      const { _data = {} } = _chartsViews[_chartsViews.length - 1]
      const { _itemLayouts, _nameList } = _data
      const _posiList = []
      each(_itemLayouts, (item, index) => {
        if (item) {
          _posiList.push({
            name: _nameList[index],
            limit: item[1]
          })
        }
      })
      if (!isEqual(this.jlPointPosi, _posiList)) {
        this.jlPointPosi = _posiList
      }
    },
    /**
     * desc: 聚类图区域框选
     * param {type}
     * return {type} void
     */
    eLineBrushEndHandle(params = {}) {
      const { areas = [] } = params
      const { range = [] } = areas[0]
      if (range.length > 1) {
        const _selecetedArea = []
        each(this.jlPointPosi, item => {
          const { name, limit } = item
          if (limit >= range[0] && limit <= range[1]) {
            _selecetedArea.push(name)
          }
        })
        if (isEqual(this._selecetedArea, _selecetedArea)) {
          return
        }
        this.jlSelectedData = _selecetedArea
        const { series, xAxis, legend } = this.zxData
        each(series, (item, index) => {
          let _color = '#749f83'
          let _opacity = 0.6
          let _w = 1
          if (includes(_selecetedArea, index.toString())) {
            _color = 'rgba(255,0,0,1)'
            _opacity = 1
            _w = 3
          }
          item.lineStyle = {
            color: _color,
            opacity: _opacity,
            width: _w
          }
        })
        this.userSelectedAreaMode()
        this.zxData = merge({}, eLineOptions, {
          legend,
          xAxis,
          series
        })
      }
    },
    /**
     * desc: 聚类图选框操作
     * param {type}
     * return {type} void
     */
    eLineBrushHandle(params) {
      const { command } = params
      // 点击取消选框时操作
      if (command === 'clear') {
        const { series, xAxis, legend } = this.zxData
        each(series, item => {
          item.lineStyle = {}
        })
        this.zxData = merge({}, eLineOptions, {
          legend,
          xAxis,
          series
        })
        this.jlSelectedData = []
        this.cAeElineData = null
      }
    },
    /**
     * desc: 聚类图点击
     * param {type}
     * return {type} void
     */
    eLineClickHandle(params = {}) {
      const { name } = params
      if (name) {
        // 画线图没有name为""
        const { series = [], xAxis, legend } = this.zxData
        each(series, (item, index) => {
          if (Number(index) === Number(name)) {
            series[index].lineStyle = {
              width: 4,
              color: 'rgb(255,0,0)',
              shadowColor: 'rgba(255, 0, 0, .9)',
              shadowBlur: 10,
              opacity: 1
            }
          } else {
            series[index].lineStyle = {
              opacity: 0.2
            }
          }
        })
        this.zxData = merge({}, eLineOptions, {
          legend,
          xAxis,
          series
        })
      }
    },
    /**
     * desc: 点击框选按钮
     * param {type}
     * return {type} void
     */
    eLineGlobalcursortakenHandle(params) {
      const { series, xAxis, legend } = this.zxData
      each(series, item => {
        item.lineStyle = {
          opacity: 0.2
        }
      })
      this.zxData = merge({}, eLineOptions, {
        legend,
        xAxis,
        series
      })
    },
    /**
     * desc: 整理日历数据
     * param {type}
     * return {type} void
     */
    modifycAeCalendarData(_serList, _timeList) {
      this.cAeCalendarData = merge({}, eCalendarOptions, {
        calendar: [
          {
            range: [head(_timeList), last(_timeList)]
          }
        ],
        series: [
          {
            type: 'scatter',
            coordinateSystem: 'calendar',
            data: _serList,
            label: {
              show: true,
              position: 'top',
              formatter: function(val = {}) {
                const { name } = val
                return name
              },
              color: '#fff'
            }
          }
        ]
      })
    },
    /**
     * desc: 整理日历查看中折线图数据
     * param {type}
     * return {type} void
     */
    modifycAeElineData(data = []) {
      const _listLen = data[0] ? data[0].length : 0
      const _dataLen = data.length
      const _newlist = []
      for (let i = 0; i < _listLen; i++) {
        let _sum = 0
        each(data, item => {
          _sum += Number(item[i])
        })

        _newlist.push(_sum / _dataLen)
      }
      const _zxAxiasList = []
      for (let i = 0; i < 24; i++) {
        _zxAxiasList.push(i + ':00')
      }

      return {
        cAeAxiasList: _zxAxiasList,
        cAeSerList: _newlist
      }
    },
    /**
     * desc: 整理聚类图区域选择数据
     * param {type}
     * return {type} void
     */
    modifySelecteAreaData() {
      const { series = [] } = this.zxData
      const _selectedData = []
      each(this.jlSelectedData, item => {
        _selectedData.push(series[item])
      })
      const _serList = []
      const _timeList = []
      const _dataList = []
      each(_selectedData, (item = {}) => {
        const { name, data } = item
        _serList.push({
          name: name,
          value: [name, 5]
        })
        _timeList.push(name)
        _dataList.push(data)
      })

      return {
        serList: _serList,
        timeList: _timeList,
        dataList: _dataList
      }
    },
    /**
     * desc: 整理聚类图点击日历后弹框中折线图数据
     * param {type}
     * return {type} void
     */
    modifycAeChartData(cAeAxiasList, cAeSerList) {
      return merge({}, eLineOptions, {
        xAxis: {
          type: 'category',
          scale: true,
          data: cAeAxiasList
        },
        series: [
          {
            type: 'line',
            name: '平均用气量',
            data: cAeSerList
          }
        ],
        grid: {
          top: 30,
          left: '8%',
          right: 20
        }
      })
    },
    /**
     * desc: 点击聚类图图中显示日历
     * param {type}
     * return {type} void
     */
    jlShowDateClick() {
      if (this.jlSelectedData.length <= 0) {
        return this.$Notice.warning({
          title: '提示信息',
          desc: '请选择区域后再点击操作'
        })
      }
      const { serList, timeList, dataList } = this.modifySelecteAreaData()
      this.cAeModuleFlag = true
      this.calendarAndElineTpl = 'CalendarAndELine'
      this.modifycAeCalendarData(serList, timeList)
      const { cAeAxiasList = [], cAeSerList = [] } = this.modifycAeElineData(dataList)
      this.cAeElineData = this.modifycAeChartData(cAeAxiasList, cAeSerList)
    },
    /**
     * desc: 聚类图查看日历中选择用气模式
     * param {type}
     * return {type} void
     */
    changeUsegasMode(mode) {
      this.cAeUserSelectedMode = mode
    },
    /**
     * desc: 聚类图查看日历详情中点击显示日期,将用户选择数据对应的日期进行星期转换并显示
     * param {type}
     * return {type} void
     */
    changeShowDate(val) {
      this.showcAeUsegasWeek = val
      if (!val) {
        this.cAeUsegasWeekList = []
        return
      }
      const { series = [] } = this.zxData
      const _serNameList = []
      each(this.jlSelectedData, item => {
        _serNameList.push(dayjs(series[item].name).day())
      })
      const _newList = uniq(_serNameList)
      const _weekList = []
      each(_newList, item => {
        _weekList.push(week[item])
      })
      this.cAeUsegasWeekList = _weekList
    },
    /**
     * desc: 添加用气模式
     * param {type}
     * return {type} void
     */
    userSelectedAreaMode() {
      const { timeList = [], dataList = [] } = this.modifySelecteAreaData()
      const { cAeAxiasList, cAeSerList } = this.modifycAeElineData(dataList)
      this.currentSelecteAreaMode = {
        name: join(this.jlSelectedData, '、'),
        timeList,
        dataList,
        avgChartData: {
          axiasList: cAeAxiasList,
          serList: cAeSerList
        }
      }
    },
    /**
     * desc: 删除指定区域选择用气模式
     * param {type}
     * return {type} void
     */
    deleteUsegasMode(index) {
      this.usegasModeList.splice(index, 1)
    },
    /**
     * desc: 日历折线图中点击确定
     * param {type}
     * return {type} void
     */
    handlecAeModuleOk() {
      this.cAeUsegasMode = this.cAeUserSelectedMode || {
        label: '主用气量模式',
        value: 1
      }
      if (this.showcAeUsegasWeek) {
        this.cAeUsegasWeekStr = join(this.cAeUsegasWeekList)
      } else {
        this.cAeUsegasWeekStr = ''
      }
      if (this.currentSelecteAreaMode) {
        this.usegasModeList.push(this.currentSelecteAreaMode)
        this.currentSelecteAreaMode = null
      }
      this.handlecAeModuleCancel()
    },
    /**
     * desc: 日历折线图中点击取消
     * param {type}
     * return {type} void
     */
    handlecAeModuleCancel() {
      this.cAeModuleFlag = false
      this.calendarAndElineTpl = null
      this.cAeCalendarData = null
      this.cAeElineData = null
    }
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
